<template>
  <div>
    <div style="padding: 0 15px">
      <div class="wjsc">永久基本农田占用补划更新包</div>
      <div class="xz">
        <div></div>
        <a-button type="primary" size="small" @click="openwd"
          >帮助文档</a-button
        >
      </div>
      <a-table
        bordered
        rowKey="id"
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
      >
        <span
          slot="action"
          slot-scope="text, record"
          v-if="record.filename != ''"
        >
          <a @click="del(record)">删除</a>&nbsp;&nbsp;<a @click="down(record)"
            >下载</a
          >
        </span>
        <span slot="add" slot-scope="text, record, index">
          <a-button
            @click="exportselect(text, record, index)"
            type="primary"
            size="small"
            v-if="record.filename == ''"
            >选择文件</a-button
          >
          <span v-if="record.filename == ''" style="margin-left: 5px;">{{
            text == "" ? "未选择任何文件" : text
          }}</span>
          <a-button class="btn" @click="upWj" v-if="record.filename == ''"
            >上传</a-button
          >
        </span>
      </a-table>
    </div>
  </div>
</template>
  
  <script>
import {
  helpFileView,
  uploadshow,
  deletedate,
  downloads,
} from "../../../api/api";
import axios from "axios";
export default {
  data() {
    return {
      columns: [
        {
          title: "IDX",
          dataIndex: "",
          key: "rowIndex",
          width: 50,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          title: "类别",
          dataIndex: "type",
          align: "center",
        },
        {
          title: "文件名",
          dataIndex: "filename",
          align: "center",
        },
        {
          title: "上传时间",
          dataIndex: "adddate",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "action",
          align: "center",
          scopedSlots: { customRender: "action" },
        },
        {
          title: "添加",
          dataIndex: "add",
          align: "center",
          scopedSlots: { customRender: "add" },
        },
      ],
      dataSource: [],
      obj: {},
      isfile: false,
    };
  },
  mounted() {
    this.getdatalist();
  },
  methods: {
    async getdatalist() {
      const data = await uploadshow({ jbxxsec: this.$route.query.id });
      if (data.result.length == 0) {
        data.result.push(
          {
            type: "数据压缩包(.rar或.zip)",
            add: "",
            filekind: "1",
            filename: "",
          },
          {
            type: "加密文件(.sm3)",
            add: "",
            filekind: "2",
            filename: "",
          }
        );
        this.dataSource = data.result;
      } else {
        console.log(data.result[0].filename != "", "arr");
        if (data.result[0].filekind == 1) {
          data.result.push({
            type: "加密文件(.sm3)",
            add: "",
            filekind: "2",
            filename: "",
          });
        } else {
          data.result.push({
            type: "数据压缩包(.rar或.zip)",
            add: "",
            filekind: "1",
            filename: "",
          });
        }
        let arr = data.result.filter((item) => item.filekind == 1);
        let btt = data.result.filter((item) => item.filekind == 2);
        const ctt = arr.concat(btt);
        ctt.map((item) => {
          item["add"] = "";
          item["action"] = "";
          item["type"] =
            item.filekind == 1 ? "数据压缩包(.rar或.zip)" : "加密文件(.sm3)";
          return item;
        });

        if (ctt.length == 3) {
          this.dataSource = ctt.splice(0, 2);
        } else {
          this.dataSource = ctt;
        }

        console.log(ctt, "ctt");
      }
    },
    exportselect(text, record, index) {
      console.log(text, record, index, "1111");

      // 创建一个隐藏的input元素
      const input = document.createElement("input");
      input.type = "file";
      input.accept = "file";
      input.style.display = "none";

      // 监听input元素的change事件
      input.addEventListener("change", (event) => {
        const file = event.target.files[0];
        console.log(file, "files");
        this.dataSource[index].add = file.name;
        // 在这里可以对文件进行处理，比如上传到服务器或进行其他操作
        let formData = new FormData();
        formData.append("file", file);
        formData.append("fkflow", "002");
        formData.append("jbxxsec", this.$route.query.id);
        formData.append("kindvalue", record.filekind);
        formData.append("isedit", "0");
        this.obj = formData;
        this.isfile = true;
      });

      // 触发input元素的点击事件
      input.click();
    },
    ///上传
    async upWj() {
      console.log(this.obj, "obj");
      if (this.isfile == false) {
        this.$warning({
          title: "请选择文件",
          okText: "确定",
        });
      } else {
        axios
          .post(
            process.env.VUE_APP_API_BASE_URL + `/fileupdates/zfiles/upload`,
            this.obj,
            {
              headers: {
                "Content-Type": "multipart/form-data",
                "Jmt-Token": localStorage.getItem("token"),
              },
            }
          )
          .then((res) => {
            if(res.data.code == 200)
            {
              this.$success({
              title: res.data.message,
              okText: "确定",
            });
            this.isfile = false;
            this.getdatalist();
            }else
            {
              this.$warning({
              title: res.data.message,
              okText: "确定",
            });
            }
          
          });
      }
    },
    //打开帮助文档
    openwd() {
      const params = {
        fileNo: 1,
      };
      helpFileView(params).then((res) => {
        const blob = new Blob([res], { type: "application/pdf" });
        // 创建一个指向Blob的URL
        const url = window.URL.createObjectURL(blob);
        // 在新标签页中打开PDF
        window.open(url);
      });
    },
    //删除
    async del(data) {
      let that = this;
      this.$confirm({
        title: "确定要删除吗?",
        cancelText: "取消",
        okText: "确定",
        onOk: () => {
          return new Promise(async (resolve, reject) => {
            const params = {
              id: data.id,
              isedit: 0,
              fkflow: data.fkFlow,
              filekind: data.filekind,
              datedesc: data.jbxxSec,
            };
            const res = await deletedate(params);
            if (res.code == 200) {
              this.$message.success("删除成功");
              resolve();
              that.getdatalist();
            } else {
              this.$message.error(res.message);
              reject();
            }
          }).catch();
        },
      });
    },
    //下载
    async down(data) {
      var name = data.filename;
      const res = await downloads({ fileName: data.filepath });
      // 将富文本内容转换为Blob对象
      const blob = new Blob([res], { type: "text/html" });
      const url = window.URL.createObjectURL(blob);
      // 创建一个a标签，设置href属性为URL对象的URL，设置download属性为要保存的文件名
      const a = document.createElement("a");
      a.href = url;
      a.download = `${name}`;
      a.style.display = "none";
      document.body.appendChild(a);
      // 模拟点击a标签来下载文件
      a.click();
      // 释放URL对象
      window.URL.revokeObjectURL(url);
    },
  },
};
</script>
  
  <style lang="less" scoped>
.wjsc {
  margin-top: 10px;
  padding-top: 6px;
  padding-bottom: 6px;
  display: table;
  width: 100%;
  padding-left: 25px;
  border-bottom: 1px solid rgba(77, 82, 89, 0.05);
  background-color: #48b0f7 !important;
  color: #fff !important;
}
.xz {
  border: 1px solid #f0f0f0;
  padding: 10px;
  display: flex;
  justify-content: space-between;
}
.btn {
  margin-left: 60px;
}
</style>